package local.blueheart.springcloud.rabbitmq.common;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.UUID;

public class BHFailCustomConsumer extends DefaultConsumer {

    private static final Logger LOGGER = LoggerFactory.getLogger(BHFailCustomConsumer.class);

    private String consumerName = "defaultConsumer";

    private long delayTime = 100L;

    public BHFailCustomConsumer(Channel channel,long delayTime, String ...name) {
        super(channel);
        try {
            channel.basicQos(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.delayTime = delayTime;
        if(name!=null) {
            this.consumerName = name[0];
        }else{
            this.consumerName = "defaultConsumer "+ UUID.randomUUID().toString();
        }
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        String msg = new String(body,"utf-8");
        LOGGER.debug(this.consumerName +"_"+msg);
        try {
            Thread.sleep(delayTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        getChannel().basicAck(envelope.getDeliveryTag(),false);
    }
}
